package org.jeecg.modules.cqb.docFile.controller;

import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.cqb.util.DocUtils;
import org.jeecg.modules.cqb.util.FTPUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @ProjectName cqb
 * @Package org.jeecg.modules.cqb.project.file.controller
 * @Name NdeUploadFileServer
 * @Author ChenJ
 * @Date 2021/12/2 0007 上午 11:07
 * @Version 1.0  上传文件到文件服务器（CentOS文件服务器）
 */
@RestController
@RequestMapping(value = "/uploadFileServer")
public class NdeUploadFileServerController {

    @ApiOperation(value = "文件上传到文件服务器")
    @RequestMapping(value = "/uploadFolder/**", method = RequestMethod.POST)
    public Result<Object> uploadFolder(HttpServletRequest request, HttpServletResponse response) {
        Result<Object> result = new Result<>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
            String fielType = extractPathFromPattern(request);
            String bizPath = request.getParameter("biz");
            byte[] bytes = file.getBytes();
            String fileNmae =  file.getOriginalFilename();
            FTPUtil.sshSftp(response,bytes, file.getOriginalFilename(),"put",fielType);
            result.setMessage(fileNmae);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("上传失败，请联系管理员！");
    }

    @ApiOperation(value = "从服务器上获取文件")
    @GetMapping(value = "/downloadFolder/**")
    public void downloadFolder(HttpServletRequest request,HttpServletResponse response) {
        try {
            String imgPath = extractPathFromPattern(request);
            FTPUtil.sshSftp(response, null ,imgPath,"get","img");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "从服务器上删除文件")
    @GetMapping(value = "/deleteFolder/**")
    public void deleteFolder(HttpServletRequest request,HttpServletResponse response) {
        try {
            String file = request.getParameter("file");// 获取上传文件对象
            String fielType = extractPathFromPattern(request);
            FTPUtil.sshSftp(response, null ,file,"del",fielType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

    @ApiOperation(value = "从服务器上获取协议 doc")
    @RequestMapping(value = "/downloadXy", method = RequestMethod.GET)
    public void downloadXy(HttpServletResponse response) {
        try {
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("tittle", "啤酒厂拆迁协议");
            dataMap.put("date", "2021-10-21");
            dataMap.put("money", "15260.30万");
            dataMap.put("userName", "张大千");
            DocUtils.saveWordWeb(response, dataMap, "测试协议");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户信息导出word  --- easypoi
     * @throws IOException
     */
    @RequestMapping("/exportUserWord2")
    public void exportUserWord2(HttpServletRequest request, HttpServletResponse response,
                                String fileName,String projectName,String ownerName,String geoCode) throws IOException{
        Map<String, Object> params = new HashMap<>();

        // 渲染文本
        params.put("project_name", projectName);
        params.put("owner_name", ownerName);
        params.put("geo_code", geoCode);

//        ImageEntity item = new ImageEntity();
//        item.setWidth(100);
//        item.setHeight(100);
//        item.setData(file2Byte("D:\\cccc.png"));
//        item.setType(ImageEntity.Data);
//        params.put("picture", item);

        try {
            FTPUtil.sshSftp(fileName+".docx", params, request, response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static byte[] file2Byte(String filePath) {
        byte[] fileBytes = null;
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }
}

